import HealthReportApi from '@/api/report'
import { reactive, toRefs } from 'vue'

import defaultData from '@/models/healthReport'

export default function() {
  const state = reactive({
    healthReport: JSON.parse(JSON.stringify(defaultData)) // 防止healthData被篡改
  })
  // 获取健康报告
  const getHealthReport = (params: any) => {
    HealthReportApi
      .getHealthReport({
        id: params.id,
        sn: params.sn,
        timestamp: params.timestamp,
        auth: params.auth,
        idCardNo: params.idCardNo,
      })
      .then(res => {
        for (const key in res.data) {
          if (res.data[key] && res.data[key] !== null) {
            state.healthReport[key] = res.data[key]
            filterData(state.healthReport[key], res.data[key], defaultData[key])
          } else {
            state.healthReport[key] = defaultData[key] // 设置默认值
          }
        }
      })
  }

  /**
   * 去掉返回数据中的null 设置成默认值
   * @param resultObj 页面显示的数据 state.healthReport
   * @param obj 接口返回的数据 res.data.data
   * @param defaultObj 默认的数据 healthData
   */
  const filterData = (resultObj: any, obj: any, defaultObj: any) => {
    let type = Object.prototype.toString.call(resultObj)
    if (type === '[object Object]') {
      for (const cKey in resultObj) {
        if (obj[cKey] && obj[cKey] !== null) {
          resultObj[cKey] = obj[cKey]
          filterData(resultObj[cKey], obj[cKey], defaultObj[cKey])
        } else {
          resultObj[cKey] = defaultObj[cKey] || ''
        }
      }
    }
  }

  return {
    getHealthReport,
    ...toRefs(state),
    filterData
  }
}
